package com.ruike.alisurface.printer;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;

import com.android.print.sdk.PrinterConstants;

/**
 * Author：voodoo
 * CreateTime：2021/7/23 9:47
 * Description：打印机的操作类
 */
public class PrinterOperateUtils {

    static PrinterOperateUtils printerOperateUtils;

    boolean isConnected = false;
    UsbOperation opertion;

    String PRINTER_VID_KEY = "printerUsbVid";
    String PRINTER_PID_KEY = "printerUsbPid";

    public static PrinterOperateUtils getInstance() {
        if (printerOperateUtils == null) {
            synchronized (PrinterOperateUtils.class) {
                if (printerOperateUtils == null) {
                    printerOperateUtils = new PrinterOperateUtils();
                }
            }
        }
        return printerOperateUtils;
    }

    public boolean isConnected() {
        return isConnected;
    }

    /**
     * 链接USB打印机设备
     */
    public void connectUsbPrinter(Context context) {
        if (!isConnected) {
            opertion = new UsbOperation(context, myHandler);
            opertion.usbAutoConn((UsbManager) context.getSystemService(Context.USB_SERVICE));
        }
    }

    /**
     * 断开链接USB打印机设备
     */
    public void unConnectUsbPrinter() {
        if (isConnected) {
            opertion.close();
            opertion = null;
            isConnected = false;
        }
    }

    /**
     * 用于接受连接状态消息的 Handler
     */
    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PrinterConstants.Connect.SUCCESS: // 链接成功
                    isConnected = true;
                    break;
                case PrinterConstants.Connect.FAILED: // 链接失败
                case PrinterConstants.Connect.CLOSED: // 链接关闭
                case PrinterConstants.Connect.NODEVICE: // 没有可用设备
                    isConnected = false;
                    break;
            }
        }
    };

//    /**
//     * 获取Usb设备
//     *
//     * @return {@link List <UsbDevice>}
//     */
//    public List<UsbDevice> getPrinterUsbDevice() {
//        UsbManager usbManager = (UsbManager) context.getSystemService(USB_SERVICE);
//        HashMap<String, UsbDevice> deviceHashMap = usbManager.getDeviceList();
//        Collection<UsbDevice> deviceCollection = deviceHashMap.values();
//        return new ArrayList<>(deviceCollection);
//    }
//
//    /**
//     * 链接USB设备
//     */
//    private void connectingUsbDevice(UsbDevice usbDevice) {
//
//        if (handler == null || usbFactory == null || usbManager == null) {
//            throw new RuntimeException("使用前请先调用initial()进行初始化！");
//        }
//
//        if (usbDevice == null) {
//            throw new RuntimeException("指定的USBDevice设备为空！");
//        }
//
//        if (isConnecting || usbFactory.getconnectstate()) { // 连接中，先关闭链接
//            usbFactory.CloseUSB(); // 关闭USB链接
//            isConnecting = false;
//        }
//
//        // 检查USB权限,有权限则链接设备并保存连接状态,没有权限则申请权限
//        if (usbManager.hasPermission(usbDevice)) { // 有权限
//            isConnectSuccess = usbFactory.connectUsb(usbManager, usbDevice);
//            if (isConnectSuccess) {
//                SharedUtils.getInstance().putInt(PRINTER_VID_KEY, usbDevice.getVendorId());
//                SharedUtils.getInstance().putInt(PRINTER_PID_KEY, usbDevice.getProductId());
//                if (onPrinterPrintListener != null) {
//                    onPrinterPrintListener.onPrinterConnect(true, "打印机连接成功");
//                }
//            } else {
//                if (onPrinterPrintListener != null) {
//                    onPrinterPrintListener.onPrinterConnect(false, "打印机未连接成功");
//                }
//            }
//        } else { // 没有USB权限
//            PendingIntent permissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(packageName), 0);
//            usbManager.requestPermission(usbDevice, permissionIntent);
//            if (onPrinterPrintListener != null) {
//                onPrinterPrintListener.onPrinterConnect(false, "请对打印机设备权限进行授权");
//            }
//        }
//
//    }

    // ================================================================================== 打印方法Api

    public void printOrder(Resources resources, OrderTicketBean.DataBean orderTicketBean) {
        if (isConnected) {
            PrintUtils.getInstance().printOrderTicket(opertion.getPrinter(), resources, orderTicketBean);
        }
    }

    // ===================================================================================== 回调监听

//    public OnPrinterPrintListener onPrinterPrintListener;
//
//    public void setOnPrinterPrintListener(OnPrinterPrintListener onPrinterPrintListener) {
//        this.onPrinterPrintListener = onPrinterPrintListener;
//    }
//
//    public interface OnPrinterPrintListener {
//        /**
//         * 未设置打印机设备
//         */
//        void onNotSetPrinter();
//
//        /**
//         * 链接监听回调
//         *
//         * @param isConnect 是否链接成功
//         * @param msg       提示消息
//         */
//        void onPrinterConnect(boolean isConnect, String msg);
//    }

}
